package com.demo.juc.volatildemo;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: jxm
 * @Description: volatile 不保证原子性
 * @Date: 2022/10/12 14:55
 * @Version: 1.0
 */
public class Test02 {
//    private volatile static int num = 0;
    private volatile static AtomicInteger num = new AtomicInteger();

    public static void add(){
//        num ++;
        num.getAndIncrement(); //+1方法 用底层的CAS
    }

    //理论结果因为：20000
    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            new Thread(()->{
                for (int j = 0; j < 1000; j++) {
                    add();
                }
            }).start();
        }

        //java中有两个线程是默认执行的一个是main一个GC
        while (Thread.activeCount()>2){
            Thread.yield();
        }

        System.out.println(Thread.currentThread().getName()+"num:"+num);
    }
}
